package me.qi.kancha.applet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis 实现的 SessionKey存储器
 *
 * @author 孙阳
 * @date 2020/10/30 14:00
 */
@Component
public class RedisDataStore implements DataStore {

    /**
     * 存储微信 SessionKey 的redis key
     */
    private static final String WX_SESSION_KEY = "wx_session_key:%s:%s";

    /**
     * 存储微信 appSecret / 企业微信 corpsecret 的redis key
     */
    private static final String WX_APP_SECRET = "wx_secret:%s";

    /**
     * 存储微信 / 企业微信 AccessToken 的redis key
     */
    private static final String WX_ACCESS_TOKEN = "wx_token:%s";

    @Autowired
    private StringRedisTemplate redisTemplate;

    public RedisDataStore(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public String readSessionKey(String appId, String openid) {
        return redisTemplate.opsForValue().get(String.format(WX_SESSION_KEY, appId, openid));
    }

    @Override
    public void storeSessionKey(String appId, String openid, String sessionKey) {
        String key = String.format(WX_SESSION_KEY, appId, openid);
        redisTemplate.opsForValue().set(key, sessionKey, 60 * 24 * 30, TimeUnit.MINUTES);
    }

    @Override
    public String readSecret(String appId) {
        return redisTemplate.opsForValue().get(String.format(WX_APP_SECRET, appId));
    }

    @Override
    public void storeSecret(String appId, String appSecret) {
        String key = String.format(WX_APP_SECRET, appId);
        redisTemplate.opsForValue().set(key, appSecret);
    }

    @Override
    public String readVWorkToken(String appId) {
        return redisTemplate.opsForValue().get(String.format(WX_ACCESS_TOKEN, appId));
    }

    @Override
    public void storeVWorkToken(String appId, String token) {
        String key = String.format(WX_ACCESS_TOKEN, appId);
        redisTemplate.opsForValue().set(key, token, 7100, TimeUnit.SECONDS);
    }
}
